package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

/**
参考：https://go.dev/doc/tutorial/web-service-gin
*/
func main() {
	router := gin.Default()
	router.GET("/albums", getAlbums)
	router.POST("/albums", postAlbums)
	router.GET("/albums/:id", findById)
	router.Run("0.0.0.0:80")
}

type album struct {
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	Artist string  `json:artist`
	Price  float64 `json:price`
}

var albums = []album{
	{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
	{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
	{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

/**
相册列表
*/
func getAlbums(c *gin.Context) {
	c.IndentedJSON(http.StatusOK, albums)
}

/** 上传相册
curl --location --request POST 'localhost/albums' \
--header 'Content-Type: application/json' \
--data-raw ' {
        "id": "4",
        "title": "你好12312",
        "Artist": "罗俊华",
        "Price": 5841
    }'
*/
func postAlbums(c *gin.Context) {
	var newAlbum album
	if err := c.BindJSON(&newAlbum); err != nil {
		log.Fatal(err)
		return
	}
	albums = append(albums, newAlbum)
	c.IndentedJSON(http.StatusCreated, newAlbum)
}

/**
根据id查看相册详情
*/
func findById(c *gin.Context) {
	id := c.Param("id")
	for _, alb := range albums {
		if alb.ID == id {
			c.IndentedJSON(http.StatusOK, alb)
			return
		}
	}
	c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
